import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Brackets, Like, Not, Repository } from 'typeorm';
import { CreateOrderDto } from './dto/create-order.dto';
import { Order } from './entities/order.entity';
import { OrderGateway } from './order.gateway';
import * as dayjs from 'dayjs';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    private readonly ws: OrderGateway,
  ) {}
  //订单状态码
  // status = 1 待确认
  // status = 2 已确认
  // status = 3 已完成
  // status = 4 已取消
  // status = 5 待支付

  //创建订单
  async create(createOrderDto: CreateOrderDto) {
    await this.orderRepository.save(createOrderDto);
    this.ws.server.emit('addOrder', true);
    return;
  }

  async createUnpay(createOrderDto: CreateOrderDto) {
    await this.orderRepository.save(createOrderDto);
    this.ws.server.emit('addOrder', true);
    return;
  }

  async findByPage(skip: number, take: number) {
    return await this.orderRepository.find({
      order: { id: 'DESC' },
      skip,
      take,
    });
  }
  async findAll() {
    return await this.orderRepository.find({ order: { id: 'DESC' } });
  }
  //查所有条数
  async findCount() {
    return this.orderRepository.createQueryBuilder('order').getCount();
  }

  async findUserful(userId: number) {
    return await this.orderRepository.find({
      where: [
        { status: Not(4), userId },
        { status: Not(5), userId },
      ],
      order: { id: 'DESC' },
    });
  }
  //查询所有未支付订单
  async findUnpay(userId: number) {
    return await this.orderRepository.find({
      where: { status: 5, userId },
      order: { id: 'DESC' },
    });
  }
  //查询当天订单 用于统计金额
  async findDay() {
    const day = new Date().getDate();
    return await this.orderRepository
      .createQueryBuilder('order')
      .where('to_days(order.create_time) = to_days(now())')
      .getMany();
  }
  //查询本周订单 用于统计金额
  async findThisWeek() {
    return await this.orderRepository
      .createQueryBuilder('order')
      .where('DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(order.create_time)')
      .andWhere(
        new Brackets((qb) => {
          qb.where('order.status = 2')
            .orWhere('order.status = 3')
            .orWhere('order.status = 6');
        }),
      )
      .getMany();
  }
  //查询进五周订单 用于统计金额
  async findLastWeek() {
    const now = dayjs();
    let start = now.subtract(7, 'day').toDate();
    let end = now.subtract(14, 'day').toDate();
    return await this.orderRepository
      .createQueryBuilder('order')
      .where('order.create_time BETWEEN :start AND :end', {
        start,
        end,
      })
      .andWhere(
        new Brackets((qb) => {
          qb.where('order.status = 2')
            .orWhere('order.status = 3')
            .orWhere('order.status = 6');
        }),
      )
      .getMany();
  }

  findByUser(userId: any) {
    return this.orderRepository.find({ where: { userId } });
  }

  update(id: number, status: number) {
    return this.orderRepository.update(id, { status: status });
  }

  remove(id: number) {
    return `This action removes a #${id} order`;
  }
}
